﻿namespace BEGDC.CC.Web.Control
{
    #region Using Directives

    using System;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using Utility.Extensions;

    #endregion

    /// <summary>
    ///   Summary description for UserSearchControl.
    /// </summary>
    [DefaultProperty("Text"), ToolboxData("<{0}:UserSearchControl runat=server></{0}:UserSearchControl>")]
    [ValidationProperty("EmployeeName"), ControlValueProperty("EmployeeName")]
    public class UserSearchControl : WebControl, IPostBackDataHandler
    {
        private readonly TextBox box;
        private readonly HtmlInputHidden empId = new HtmlInputHidden();
        private readonly HtmlInputHidden empNameCn = new HtmlInputHidden();
        private readonly HtmlInputHidden empNo = new HtmlInputHidden();
        private readonly HtmlInputHidden selfId = new HtmlInputHidden();
        //private HtmlInputHidden depts;

        public UserSearchControl()
        {
            this.TitleControlName = string.Empty;
            this.TelephoneControlName = string.Empty;

            this.box = new TextBox
            {
                CssClass = "VALUEBOX"
            };

            this.box.Attributes["ContentEditable"] = "false";

            this.empNo.Value = string.Empty;
            this.selfId.Value = string.Empty;
            this.empId.Value = "0";
            this.empNameCn.Value = string.Empty;
        }

        public string Role { get; set; }

        public string EmployeeName
        {
            get
            {
                return this.box.Text;
            }
            set
            {
                this.box.Text = value;
            }
        }

        public string EmployeeNameCN
        {
            get
            {
                return this.empNameCn.Value;
            }
            set
            {
                this.empNameCn.Value = value;
            }
        }

        /// <summary>
        ///   This is actually the EmployeeNo.
        /// </summary>
        public string EmployeeID
        {
            get
            {
                return this.empNo.Value;
            }
            set
            {
                this.empNo.Value = value;
            }
        }

        /// <summary>
        ///   This is actually the EmployeeID.
        /// </summary>
        public int EmployeeFlowID
        {
            get
            {
                return Convert.ToInt32(this.empId.Value);
            }
            set
            {
                this.empId.Value = value.ToString();
            }
        }

        public string SelfID
        {
            get
            {
                return this.selfId.Value;
            }
            set
            {
                this.selfId.Value = value;
            }
        }

        public string Departments { get; set; }

        public string CssClassName
        {
            get
            {
                return this.box.CssClass;
            }
            set
            {
                this.box.CssClass = value;
            }
        }

        public TextBox Box
        {
            get
            {
                return this.box;
            }
        }

        public string TitleControlName { get; set; }

        public string TelephoneControlName { get; set; }

        public bool IsPostBack { get; set; }

        #region IPostBackDataHandler Members

        public void RaisePostDataChangedEvent()
        {
            if (this.OnEmployeeChanged != null)
            {
                this.OnEmployeeChanged(this, null);
            }
        }

        public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            try
            {
                this.box.Text = postCollection[this.UniqueID + "_Employee_Name"];
                this.empNameCn.Value = postCollection[this.UniqueID + "_Employee_NameCN"];
                this.empId.Value = postCollection[this.UniqueID + "_Employee_Flow_ID"];

                string empNumber = postCollection[this.UniqueID + "_Employee_ID"];
                if (empNumber != this.empNo.Value)
                {
                    this.empNo.Value = postCollection[this.UniqueID + "_Employee_ID"];
                    return true;
                }
            }
            catch
            {
            }

            return false;
        }

        #endregion

        protected override void Render(HtmlTextWriter output)
        {
            this.Page.ClientScript.RegisterHiddenField(this.ClientID, this.EmployeeName);

            output.AddAttribute(HtmlTextWriterAttribute.Type, "hidden");
            output.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);
            output.RenderBeginTag(HtmlTextWriterTag.Input);
            output.RenderEndTag();

            this.Controls.Clear();

            var table = new HtmlTable
            {
                Border = 0,
                CellSpacing = 0,
                CellPadding = 0
            };

            var row = new HtmlTableRow();

            var cell1 = new HtmlTableCell();
            this.box.ID = this.ID + "_Employee_Name";
            this.box.Attributes.Add("runat", "server");
            this.box.Width = Unit.Pixel(150);

            this.empNameCn.ID = this.ID + "_Employee_NameCN";
            this.empId.ID = this.ID + "_Employee_Flow_ID";

            this.empNo.ID = this.ID + "_Employee_ID";
            cell1.Controls.Add(this.box);
            cell1.Controls.Add(this.empNo);
            cell1.Controls.Add(this.empNameCn);
            cell1.Controls.Add(this.empId);

            //self););
            this.selfId.ID = this.ID + "_Self_ID";
            cell1.Controls.Add(this.selfId);

            var cell2 = new HtmlTableCell
            {
                InnerHtml = "&nbsp;<img id=\"imgSearchUser\" runat=\"server\" title=\"Click to search employees (搜索员工)\" align=\"middle\" src=\"" + this.ResolveUrl("~/images/Search.gif") + "\" onclick=\"javascript:ShowUserSelectForm_" + this.ClientID + "();\" style=\"cursor:hand\" /> "
            };
            row.Cells.Add(cell1);
            row.Cells.Add(cell2);
            table.Rows.Add(row);
            this.Controls.Add(table);
            this.RenderChildren(output);
            this.WriteClientScript(output);
        }

        private void WriteClientScript(HtmlTextWriter output)
        {
            output.WriteLine("<script language=\"javascript\">");
            output.WriteLine("<!--");
            output.WriteLine("function ShowUserSelectForm_" + this.ClientID + "() {");
            output.WriteLine("var $ = document.getElementById;");
            output.WriteLine("var name_box = $(\"" + this.ClientID + "_Employee_Name\");");
            output.WriteLine("var id_value = $(\"" + this.ClientID + "_Employee_ID\");");
            if (this.TitleControlName.IsNotNullOrWhiteSpace())
            {
                output.WriteLine("var title_box = $(\"" + this.TitleControlName + "\");");
            }
            if (this.TelephoneControlName.IsNotNullOrWhiteSpace())
            {
                output.WriteLine("var phoneBox = $('" + this.TelephoneControlName + "');");
            }

            output.WriteLine("	var selfid_value = $(\"" + this.ClientID + "_Self_ID\");");

            output.WriteLine("var name = name_box.value;");
            output.WriteLine("var code = window.showModalDialog('" + this.ResolveUrl("~/Workflow/SelectEngineerForm.aspx") + "?Depts=" + this.Departments + "&type=" + this.Role + "&self=" + this.selfId.Value +
                             " ','','dialogHeight:340px;dialogWidth:370px;dialogTop:px;dialogLeft:px;center:Yes;scroll:yes;resizable:no;status:no;')");
            output.WriteLine("if(code) {");
            output.WriteLine("  var temp = code.split(\"|\");");
            output.WriteLine("  name_box.value = temp[0];");
            output.WriteLine("  id_value.value = temp[1];");
            if (this.TitleControlName.IsNotNullOrWhiteSpace())
            {
                output.WriteLine("if (title_box) {title_box.value = temp[2];}");
            }
            if (this.TelephoneControlName.IsNotNullOrWhiteSpace())
            {
                output.WriteLine("if (phoneBox) {phoneBox.value = temp[3];}");
            }
            output.WriteLine("  $('" + this.ClientID + "_Employee_NameCN').value = temp[4];");
            output.WriteLine("  $('" + this.ClientID + "_Employee_Flow_ID').value = temp[5];");

            output.WriteLine("if('chain' in window) chain();");

            output.WriteLine("}");
            if (this.IsPostBack)
            {
                output.WriteLine("	var theform = document.Form1 || document.forms[\"Form1\"];");
                output.WriteLine("	theform.submit();");
            }
            output.WriteLine("}");
            output.WriteLine("//-->");
            output.WriteLine("</script>");
        }

        protected override object SaveViewState()
        {
            var objects = new object[]
            {
                this.box.Text, this.empNo.Value, this.selfId.Value, this.TitleControlName, this.TelephoneControlName, this.empNameCn.Value, this.empId.Value
            };

            return objects;
        }

        protected override void LoadViewState(object savedState)
        {
            if (savedState == null)
            {
                return;
            }

            var objects = (object[]) savedState;

            if (objects[0] != null)
            {
                this.box.Text = (string) objects[0];
            }
            if (objects[1] != null)
            {
                this.empNo.Value = (string) objects[1];
            }
            if (objects[2] != null)
            {
                this.selfId.Value = (string) objects[2];
            }
            if (objects[3] != null)
            {
                this.TitleControlName = (string) objects[3];
            }
            if (objects[4] != null)
            {
                this.TelephoneControlName = (string) objects[4];
            }
            if (objects[5] != null)
            {
                this.empNameCn.Value = (string)objects[5];
            }

            if (objects[6] != null)
            {
                this.empId.Value = (string)objects[6];
            }
        }

        public event EventHandler OnEmployeeChanged;
    }
}